package com.cloud.ebookreader.javascript;

import java.security.InvalidParameterException;

import com.cloud.ebookreader.access.Book;
import com.cloud.ebookreader.access.TocEntry;
import com.cloud.ebookreader.http.UrlQueryParameterConstants;

public class JavaScriptCreator {
	public static String createBookJavascript(String bookBlobKey, String baseUrl, Book book) {
		String title = "titleNotSet";
        String creator = "creatorNotSet";  
        
        if(book == null || book.getMetadata() == null || book.getToc().isEmpty()){
            throw new InvalidParameterException("Given book not valid... ");
        }
        
        if (book.getMetadata() != null) {
            if (book.getMetadata().getTitle() != null) {
                title = book.getMetadata().getTitle();
            }
            if (book.getMetadata().getCreator() != null) {
                creator = book.getMetadata().getCreator();
            }
        }
        
        StringBuilder sb = new StringBuilder();
        sb.append("getComponents : function() {\n");
        sb.append("return [ ");
        
        for (TocEntry toc : book.getToc()) {
            sb.append("'").append(createComponent(baseUrl,bookBlobKey,toc.getComponentName())).append("',\n");
        }
        
        //remove last 3 
        sb.delete(sb.length() - 2, sb.length());
        sb.append("];\n},\n");

        sb.append("getContents : function() {\n");
        sb.append("return [ ");

        for (TocEntry toc : book.getToc()) {
            sb.append("{title: \"").append(toc.getTitle()).append("\", src: '").append(createComponent(baseUrl,bookBlobKey,toc.getComponentName())).append("'},\n");
        }
        //remove last 3 
        sb.delete(sb.length() - 2, sb.length());
        sb.append("];\n},\n");



        sb.append("getMetaData : function(key) {\n");
        sb.append("return {\n");
        sb.append("title : \"").append(title).append("\",\n");
        sb.append("creator : \"").append(creator).append("\"\n");
        sb.append("}[key];\n},\n");

        return sb.toString();
	}
	
	private static String createComponent(String baseUrl, String bookBlobKey, String component){
        StringBuilder sb = new StringBuilder();
        
        sb.append(baseUrl);
        sb.append("/getComponent?");
        sb.append(UrlQueryParameterConstants.BOOK_BLOB_KEY);
        sb.append("=");
        sb.append(bookBlobKey);
        sb.append("&");
        sb.append(UrlQueryParameterConstants.COMPONENT_ID);
        sb.append("=");
        sb.append(component);
        
        return sb.toString();
    }
}
